package com.edgar.paysdk.wechat

import android.content.Context
import android.content.Intent
import android.util.Log
import com.edgar.paysdk.*
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelbase.BaseResp.ErrCode.*
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory

import com.tencent.mm.opensdk.modelpay.PayReq as WXPayReq
/**
 * Created by edgar on 18-1-20.
 */
class WeChatPay(context: Context) : PayPlatform(context),IWXAPIEventHandler{

    companion object {
        private @JvmStatic val TAG = "WeChatPay"
    }
    private val mWXApi:IWXAPI = WXAPIFactory.createWXAPI(mContext,PayInitialize.getWeChatAppId())

    init {
        mWXApi.registerApp(PayInitialize.getWeChatAppId())
    }

    override fun doPay(payReq: PayReq):Boolean {
        val wxPayReq = WXPayReq()
        wxPayReq.appId = payReq.getAppId()
        wxPayReq.nonceStr = payReq.getNonceStr()
        wxPayReq.prepayId = payReq.getPrePayId()
        wxPayReq.packageValue = payReq.getPackageValue()?:"Sign=WXPay"
        wxPayReq.partnerId = payReq.getPartnerId()
        wxPayReq.timeStamp = payReq.getTimeStamp()
        wxPayReq.sign = payReq.getSign()
        wxPayReq.signType = payReq.getSignType()
        return mWXApi.sendReq(wxPayReq)
    }

    override fun isMustClient(): Boolean = true
    override fun getClientName(): String = "微信"
    override fun isInstallApp(): Boolean = Utils.hasWeChatInstalled(mContext)
    override fun getPayType(): PayType = PayType.WeChat

    fun handleIntent(wxPayHandlerActivity: WXPayHandlerActivity,intent: Intent?){
        mWXApi.handleIntent(intent,this)
    }

    override fun onReq(req: BaseReq?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onResp(resp: BaseResp?) {
        if (resp?.type == ConstantsAPI.COMMAND_PAY_BY_WX) {
            Log.d(TAG, "onPayFinish, errCode = " + resp.errCode)
            when(resp.errCode){
                ERR_OK->{
                    Log.d(TAG,"WeChat pay success.")
                    mPayListener?.onSuccess(this)
                }
                ERR_USER_CANCEL->{
                    Log.d(TAG,"WeChat user cancel pay")
                    mPayListener?.onCancel(this)
                }
                ERR_COMM->{
                    val errStr = resp.errStr
                    Log.d(TAG,"WeChat pay failed,error message:${errStr}")
                    mPayListener?.onError(this,PayException(errStr))
                }
            }
        }
    }
}